package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.msg.SeckillGoodsCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_GROUP,
        topic = MQConstans.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstans.CREATE_ORDER_TAG
)
@Component
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("创建订单的消费者");
        //接受传过来的参数
        Long seckillId = orderMessage.getSeckillId();
        Long userId = orderMessage.getUserId();
        String uuid = orderMessage.getUuid();
        Map<String,Object> map = new HashMap<>();
        map.put("seckillId",seckillId);
        map.put("userId",userId);
        map.put("uuid",uuid);
        try{
            //int i = 1/0;
            String orderNo = orderInfoService.seckill(userId,seckillId);
            map.put("data",orderNo);
            map.put("code",200);

            //发送成功消息
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_SUCCESS_DEST,map);
            System.out.println("----------------------");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code", SeckillGoodsCodeMsg.SECKILL_OPT.getCode());
            map.put("msg",SeckillGoodsCodeMsg.SECKILL_OPT.getMsg());

            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_FAIL_DEST,map);
        }
    }
}
